#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : SystemApi.py
@Time : 2024/12/30 18:51
@Author: Wangwc
@Describe:  系统管理相关业务方法封装
"""
import ftplib
import os
import random
import subprocess
import telnetlib
import time

import paramiko
import requests
from ftplib import FTP_TLS

from utils.requests_tools import HttpRequest, check_response, retry_func
from utils.login import Login
from commons.logger import log
from utils.ssh_tools import create_ssh_client_as_root, create_raid_with_shell

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = 'cloud.ini'

assert_message = {'code': 200, 'msg': 'success'}
login = Login(config_name=config_name)
token = login.login()


class SystemApi:

    def __init__(self, u_token, configname=config_name):
        self.http = HttpRequest(configname, u_token=u_token)

    def check_login_status(self, MAX_RETRY=3, RETRY_INTERVAL=5):
        retry_count = 0
        while retry_count < MAX_RETRY:
            try:
                response = self.get_firmware_version_status()
                # 根据实际与服务器端确认的规则判断登录是否有效，这里假设返回的json数据中有 'status' 字段表示登录状态，'success' 表示有效，根据实际调整
                if response.get('msg') == 'success':
                    return True
                return False
            except requests.RequestException as e:
                print(f"登录验证请求出现异常: {e}，进行重试...")
                retry_count += 1
                time.sleep(RETRY_INTERVAL)
        print("多次验证登录状态失败，按登录失效处理")
        return False

    @check_response(ext="data")
    def get_firmware_version_status(self):
        """
        获取系统固件版本
        :return: 固件版本
        """
        log.debug("开始执行获取获取系统固件状态操作")
        path = "/ugreen/v1/firmware/status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取系统固件状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data")
    def get_firmware_config(self):
        """
        获取系统更新配置
        :return: 配置信息
        """
        log.debug("开始执行获取系统更新配置操作")
        path = "/ugreen/v1/firmware/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取系统更新配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data")
    def set_firmware_config(self, auto_update=0, custom_interval_time=False, interval_time=22, unit=1):
        """
        设置系统更新配置
        :param auto_update: 是否自动更新 0、通知我并让我决定是否安装 1、自动下载重要更新  2、自动下载最新更新
        :param custom_interval_time: 是否自定义更新时间
        :param interval_time: 更新时间间隔
        :param unit: 时间单位
        :return: 设置结果
        """
        log.debug("开始执行设置系统更新配置操作")
        path = "/ugreen/v1/firmware/config"
        data = {"auto_update": auto_update, "custom_interval_time": custom_interval_time,
                "interval_time": interval_time, "unit": unit}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置系统更新配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.current_version", check=assert_message)
    def get_firmware_version(self):
        """
        获取系统固件版本
        :return: 固件版本
        """
        log.debug("开始执行获取获取系统固件状态操作")
        path = "/ugreen/v1/firmware/status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取系统固件状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def check_firmware_status(self, check=1):
        """
        检查固件状态
        :return: 固件版本
        """
        log.debug("开始执行获取获取系统固件状态操作")
        path = "/ugreen/v1/firmware/status"
        params = {"check": check}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取系统固件状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_ddns_status(self):
        """
        获取DDNS状态
        :return:
        """
        log.debug("开始执行获取DDNS状态操作")
        path = "/ugreen/v1/connect/ddns/status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取DDNS状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_ddns_list(self):
        """
        获取ddns域名列表
        :return:
        """
        log.debug("开始执行获取ddns域名列表操作")
        path = "/ugreen/v1/connect/ddns/list"
        params = {"limit": 50, "offset": 1}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取ddns域名列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def stop_ddns(self):
        """
        关闭DDNS
        :return:
        """
        log.debug("开始执行关闭DDNS操作")
        path = "/ugreen/v1/connect/ddns/stop"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在关闭DDNS过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def add_ddns(self, server, domain, accessID, key, extIPV6='', externalIPV4='', internalIPV4='', ipv4Auto=1,
                 ipv4Enable=1, ipv6Enable=1, isIpv6Auto=1, ifaceV6=''):
        """
        新增DDNS
        :param server 服务商域名
        :param domain 域名
        :param accessID 阿里云accessID
        :param key 阿里云key
        :return:
        """
        log.debug("开始执行新增DDNS操作")
        path = "/ugreen/v1/connect/ddns/add"
        data = {"serviceProvider": server, "domain": domain, "accessID": accessID,
                "key": key, "extIPV6": extIPV6, "externalIPV4": externalIPV4, "internalIPV4": internalIPV4,
                "ipv4Auto": ipv4Auto, "ipv4Enable": ipv4Enable, "ipv6Enable": ipv6Enable, "isIpv6Auto": isIpv6Auto,
                "ifaceV6": ifaceV6}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在新增DDNS过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def edit_ddns(self, id,server, domain, accessID, key, extIPV6='',internalIPV4='', ipv4Auto=1,
                 ipv4Enable=1, ipv6Enable=1, isIpv6Auto=1, ifaceV6=''):
        """
        编辑DDNS
        :param id ddns id信息
        :param server 服务商域名
        :param domain 域名
        :param accessID 阿里云accessID
        :param key 阿里云key
        :return:
        """
        log.debug("开始执行编辑DDNS操作")
        path = "/ugreen/v1/connect/ddns/edit"
        data = {"id":id,"serviceProvider": server, "domain": domain, "accessID": accessID,
                "key": key, "extIPV6": extIPV6, "internalIPV4": internalIPV4,
                "ipv4Auto": ipv4Auto, "ipv4Enable": ipv4Enable, "ipv6Enable": ipv6Enable, "isIpv6Auto": isIpv6Auto,
                "ifaceV6": ifaceV6}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在编辑DDNS过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def delete_ddns(self, id):
        """
        删除DDNS
        :return:
        """
        log.debug("开始执行删除DDNS操作")
        path = "/ugreen/v1/connect/ddns/delete"
        params = {"id": id}
        try:
            response = self.http.delete(path, params=params)
            return response
        except Exception as e:
            log.error(f"在删除DDNS过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_ddns_port_mapping_status(self):
        """
        获取DDNS_port_mapping状态
        :return:
        """
        log.debug("开始执行获取DDNS_port_mapping状态操作")
        path = "/ugreen/v1/connect/ddns/port_mapping_status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取DDNS_port_mapping状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_uglink_status(self):
        """
        获取uglink状态
        :return:
        """
        log.debug("开始执行获取uglink状态操作")
        path = "/ugreen/v1/connect/uglink/status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取uglink状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def enable_uglink(self, alias):
        """
        开启uglink
        :param: alias  uglink id     示例：wang1234
        :return:
        """
        log.debug("开始执行开启uglink操作")
        path = "/ugreen/v1/connect/uglink/enable"
        params = {"alias": alias}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在开启uglink过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def disable_uglink(self):
        """
        关闭uglink
        :return:
        """
        log.debug("开始执行关闭uglink操作")
        path = "/ugreen/v1/connect/uglink/disable"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在关闭uglink程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_cloud_owner(self):
        """
        获取云端用户
        :return:
        """
        log.debug("开始执行获取云端用户操作")
        path = "/ugreen/v1/user/cloud/owner"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取云端用户过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data")
    def is_bind(self, uid):
        """
        校验是否绑定云端账号
        :param uid: 用户id 1001
        :return:
        """
        log.debug("开始执行校验是否绑定云端账号操作")
        path = f"/ugreen/v1/user/cloud/{uid}/isbind"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在校验是否绑定云端账号过程中出现异常，异常信息: {e}")
            raise

    def cloud_bind(self, ugreen_no, accessToken, account_type=1):
        """
        绑定云端账号
        :param ugreen_no:绿联云编号 901359
        :param accessToken:云端token
        :param account_type:账号类型 1:邮箱 2:手机号 3:第三方账号
        :return:
        """
        log.debug("开始执行绑定云端账号操作")
        path = "/ugreen/v1/user/cloud/bind"
        headers = {"Authorization": accessToken}
        request_data = {"ugreen_no": ugreen_no, "accessToken": accessToken, "account_type": account_type}
        try:
            response = self.http.post(path, json=request_data, headers=headers)
            return response
        except Exception as e:
            log.error(f"在绑定云端账号过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def identify_country(self):
        """
        确认云端国家节点
        :return:
        """
        log.debug("开始执行确认云端国家节点操作")
        path = "/ugreen/v1/verify/identify/country"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在确认云端国家节点过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def reset_system(self, x_curpass_token=None):
        """
        恢复出厂设置
        :return:
        """
        log.debug("开始执行恢复出厂设置操作")
        path = "/ugreen/v1/backup_restore/reset"
        request_headers = {"x-curpass-token": x_curpass_token}
        try:
            response = self.http.get(path, headers=request_headers)
            return response
        except Exception as e:
            log.error(f"在恢复出厂设置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check={'code': 200, 'msg': 'SUCCESS'})
    def get_uglink_nodeInfo_byAlias(self, cloud_host, uglink_id):
        """
        根据uglink id 获取节点信息
        :param: cloud_host :云端域名
        :param: uglink_id :wang1234
        :return:
        """
        log.debug("开始执行根据uglink id 获取节点信息操作")
        path = f"{cloud_host}/api/p2p/v2/ta/nodeInfo/byAlias"
        request_data = {"alias": uglink_id}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在根据uglink id 获取节点信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.cumtomPorts", check=assert_message)
    def get_nginx_connect(self, hostname, protocol='http', port=9999):
        """
        获取nginx网页连接信息
        :return:
        """
        log.debug("开始执行获取nginx网页连接信息操作")
        path = f'{protocol}://{hostname}:{port}/ugreen/v1/connect/nginx/get'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取nginx网页连接信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_power_up(self, time):
        """
        设置电源开机信息
        :param: time: 16:00
        :return:
        """
        log.debug("开始执行获取nginx网页连接信息操作")
        path = '/ugreen/v1/hardware/power/start'
        request_data = {"power_boot": True, "wake_on": False, "hard_drive_flag": True, "hard_drive_unit": "M",
                        "hard_drive_time": 20, "usb_hard_drive_flag": True, "usb_hard_drive_unit": "M",
                        "usb_hard_drive_time": 20,
                        "time_switches": [{"frequency": [7, 1, 2, 3, 4, 5, 6], "time": time, "action": "open"}],
                        "enable_hard_drive_sleep_log": False}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取nginx网页连接信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def power_off(self):
        """
        设备关机
        :return:
        """
        log.debug("开始执行设备关机操作")
        path = '/ugreen/v1/desktop/poweroff'
        request_data = {"update_and_poweroff": False}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在设备关机过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain(self):
        """
        获取自定义域名
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v1/connect/domain/get'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_domain(self, domain_name, enable=1):
        """
        设置自定义域名
        :param: domain_name: 域名
        :param: enable: 是否启用
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v1/connect/domain/set'
        request_data = {"enable": enable, "name": domain_name}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def desktop_search(self, key, show_type=2, order_type=3, order=0, offset=0):
        """
        桌面搜索
        :param: key:搜索关键字
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v1/desktop/search'
        request_data = {"key": key, "show_type": show_type, "order_type": order_type, "order": order, "offset": offset,
                        "limit": 6}
        # data = {"key": "应用中心", "show_type": 2, "order_type": 3, "order": 0, "offset": 0, "limit": 6}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def app_search(self, key):
        """
        应用中心搜索
        :param: key:搜索关键字
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v1/app/search'
        params = {"key": key}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def create_folder(self):
        """
        桌面搜索
        :param: key:搜索关键字
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v2/filemgr/createFolder'
        data = {"path": "/home/test3/再看看", "no_recursive_creation": True}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_user_history_list(self):
        """
        获取账号活动历史记录
        :return:
        """
        log.debug("开始执行获取自定义域名操作")
        path = '/ugreen/v1/user/history/list'
        params = {"page": 1, "size": 200}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取自定义域名过程中出现异常，异常信息: {e}")
            raise

    def get_user_wallpaper(self):
        """
        获取用户壁纸-图片流
        :return:
        """
        log.debug("开始执行获取用户壁纸-图片流操作")
        path = '/ugreen/v1/user/wallpaper'
        params = {'v': "cbb6258690caa4a211819b4df078e531"}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取用户壁纸-图片流过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_wallpaper_list(self):
        """
        获取默认壁纸列表
        :return:
        """
        log.debug("开始执行获取默认壁纸列表操作")
        path = '/ugreen/v1/user/wallpaper/list'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取默认壁纸列表过程中出现异常，异常信息: {e}")
            raise

    def get_wallpaper_stream(self, bg_path, width=160, height=96, type=0):
        """
        获取壁纸流
        :param: bg_path: 图片路径 /ugreen/wallpaper/default_09.jpg
        :param: width: 图片宽度 160
        :param: height: 图片高度 96
        :param: type: 图片类型 0
        :return:
        """
        log.debug("开始执行获取默认壁纸列表操作")
        path = '/ugreen/v1/filemgr/mediaPlayer'
        params = {"path": bg_path,
                  "width": width,
                  "height": height,
                  "type": type
                  }
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取默认壁纸列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_user_wallpaper(self, bg_path=None, bg_type=0, file=None, bg_model=0, change_wallpaper=True):
        """
        修改用户壁纸
        :param bg_path:默认壁纸路径 /ugreen/wallpaper/default_09.jpg
        :param bg_type:壁纸类型 0:默认壁纸 1:自定义壁纸 2:壁纸使用颜色
        :param file:文件流
        :param bg_model:壁纸模式 0:填充 1：居中 2：最合适 3：拉伸 4：平铺
        :param change_wallpaper:是否修改壁纸 True False
        :return:
        """
        log.debug("开始执行修改用户壁纸操作")
        path = '/ugreen/v1/user/change/wallpaper'
        data = {"bg_path": bg_path,
                "bg_type": bg_type,
                "file": file,
                "bg_model": bg_model,
                "change_wallpaper": change_wallpaper
                }
        if bg_path is not None:
            data["bg_path"] = bg_path
        elif file is not None:
            data["file"] = file
        else:
            raise ValueError("icon和file参数不能同时为空，必须有一个有值")

        try:
            response = self.http.post(path, data=data)
            return response
        except Exception as e:
            log.error(f"在修改用户壁纸过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_language_list(self):
        """
        获取当前语言列表信息
        :return:
        """
        log.debug("开始执行获取当前语言列表信息操作")
        path = '/ugreen/v1/language/list'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取当前语言列表信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.used", check=assert_message)
    def get_user_language(self):
        """
        获取当前用户语言信息
        :return:
        """
        log.debug("开始执行获取当前用户语言信息操作")
        path = '/ugreen/v1/language/user'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取当前用户语言信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_user_language(self, language):
        """
        设置当前用户语言信息
        :param language: 语言信息 en-US、zh-CN、ja-JP、de-DE
        :return:
        """
        log.debug("开始执行设置当前用户语言信息操作")
        path = '/ugreen/v1/language/user'
        request_data = {"language": language}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在设置当前用户语言信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_time_config(self):
        """
        获取当前时间配置信息
        :return:
        """
        log.debug("开始执行获取当前时间配置信息操作")
        path = '/ugreen/v1/time/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取当前时间配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_global_time_config(self, time_zone="Asia/Shanghai", time_set_type=0, time=0,
                               time_server="pool.ntp.org", date_format="YYYY-MM-dd", time_format="24",
                               date1=None, time1=None, time_show=None):
        """
        设置系统时间配置
        :param date1: 日期信息 "2025-02-20"
        :param time1: 时间信息 "16:24:56"
        :param timezone: 时区信息 "Asia/Shanghai"
        :param time_set_type: 时间设置类型 0：与服务器同步 1：手动设置
        :param time_show: 时间显示相关信息
        :param time: 时间相关参数
        :param time_server: 时间服务器地址
        :param date_format: 日期格式
        :param time_format: 时间格式
        :return:
        """
        log.debug("开始执行设置系统时间配置操作")
        path = '/ugreen/v1/time/config'
        # 初始化请求数据
        data_dict = {
            "timezone": time_zone,
            "time_set_type": time_set_type,
            "time": time,
            "time_server": time_server,
            "date_format": date_format,
            "time_format": time_format,
            "time_show": time_show
        }
        # 根据参数是否为 None 决定是否添加到请求数据中
        if date1 is not None:
            data_dict["date1"] = date1
        if time_show is not None:
            data_dict["time_show"] = time_show
        if time1 is not None:
            data_dict["time1"] = time1

        try:
            # 这里假设 self.http 是一个具备 post 方法的对象，你需要根据实际情况调整
            response = self.http.post(path, json=data_dict)
            return response
        except Exception as e:
            log.error(f"在设置系统时间配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_time_by_hand(self, time):
        """
        手动设置时间
        :param time:时间戳 1739995504
        :return:
        """
        log.debug("开始执行手动设置时间操作")
        path = '/ugreen/v1/time/verify/cloud/certificate'
        params = {'time': time}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在手动设置时间过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_time_server(self):
        """
        获取时间服务器列表
        :return: 服务器列表
        """
        log.debug("开始执行获取时间服务器列表操作")
        path = '/ugreen/v1/time/server'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取时间服务器列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def add_time_server(self, time_server):
        """
        添加时间服务器
        :return:
        """
        log.debug("开始执行添加时间服务器操作")
        path = '/ugreen/v1/time/server'
        data = {"time_server": time_server}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在添加时间服务器过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def del_time_server(self, time_server):
        """
        删除时间服务器
        :return:
        """
        log.debug("开始执行删除时间服务器操作")
        path = '/ugreen/v1/time/server/delete'
        data = {"time_server": time_server}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在删除时间服务器过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_global_language(self):
        """
        获取系统全局语言配置
        :return:
        """
        log.debug("开始执行获取系统全局语言配置操作")
        path = '/ugreen/v1/language/global'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取系统全局语言配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_global_language(self, language):
        """
        设置系统全局语言配置
        :return:
        """
        log.debug("开始执行设置系统全局语言配置操作")
        path = '/ugreen/v1/language/global'
        data = {"language": language}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置系统全局语言配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_time_config(self, date_format="YYYY/MM/dd", time_format="24"):
        """
        设置时间配置信息
        :param: date_format: 日期格式 MM/dd/YYYY
        :param: time_format: 时间格式 12
        :return:
        """
        log.debug("开始执行设置时间配置信息操作")
        path = '/ugreen/v1/user/change/dateTimeFormat'
        request_data = {"date_format": date_format, "time_format": time_format}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在设置时间配置信息过程中出现异常，异常信息: {e}")
            raise

    def get_user_headpic(self, uid):
        """
        获取用户头像流
        :param: uid 用户id  1001
        :param: time: 当前时间戳
        :return:
        """
        log.debug("开始执行获取用户头像操作")
        path = f'/ugreen/v1/user/headpic/stream/{uid}'
        params = {"t": int(time.time() * 1000)}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取用户头像过程中出现异常，异常信息: {e}")
            raise

    def get_headpic_stream(self, icon):
        """
        获取头像图片流
        :param: icon 01.png
        :return:
        """
        log.debug("开始执行获取头像图片流操作")
        path = f'/ugreen/v1/user/headpic/stream/{icon}'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取头像图片流过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.list", check=assert_message)
    def get_user_headpic_list(self):
        """
        获取用户头像列表
        :return:
        """
        log.debug("开始执行获取默认头像列表操作")
        path = '/ugreen/v1/user/headpic/list'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取默认头像列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_user_headpic(self, uid, icon=None, file=None):
        """
        更换用户头像
        :param: uid 用户id  1001
        :param: icon 头像  02.png
        :param: file:
        :return:
        """
        log.debug("开始执行更换用户头像操作")
        path = f'/ugreen/v1/user/change/headpic/{uid}'
        data = {}
        if icon is not None:
            data["icon"] = icon
        elif file is not None:
            data["file"] = file
        else:
            raise ValueError("icon和file参数不能同时为空，必须有一个有值")
        try:
            response = self.http.post(path, data=data)
            return response
        except Exception as e:
            log.error(f"在获取默认头像列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.uid", check=assert_message)
    def get_user_uid(self, username):
        """
        获取用户uid
        :param: username 当前用户名
        :return: 用户 uid
        """
        log.debug("开始执行获取用户uid操作")
        path = f'/ugreen/v1/user/name/{username}'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户uid过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_user_password(self, uid, password, old_password):
        """
        更改用户密码
        :param uid: 用户id  1001
        :param password: 新密码(加密后的密码）
        :param old_password: 旧密码(加密后的密码）
        :return:
        """
        log.debug("开始执行更改用户密码操作")
        path = '/ugreen/v1/user/change/passwd'
        request_data = {"uid": uid, "password": password, "old_password": old_password}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在更改用户密码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_user_history_list(self):
        """
        获取用户历史密码
        :return:
        """
        log.debug("开始执行获取用户历史密码操作")
        path = '/ugreen/v1/user/history/list'
        request_data = {"page": 1, "size": 200}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取用户历史密码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.List", check=assert_message)
    def get_message_list(self):
        """
        获取所有通知列表
        :return:
        """
        log.debug("开始执行获取所有通知列表操作")
        path = '/ugreen/v1/desktop/message/list'
        request_data = {"level": ["info", "important", "warning"], "page": 1, "size": 100}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取所有通知列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_read_message(self):
        """
        获取已读通知信息
        :return:
        """
        log.debug("开始执行获取已读通知信息操作")
        path = '/ugreen/v1/desktop/message/read'
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在获取已读通知信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_message_config(self):
        """
        获取通知配置信息
        :return:
        """
        log.debug("开始执行获取通知配置信息操作")
        path = '/ugreen/v1/desktop/message/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取通知配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_message_config(self):
        """
        设置通知配置信息
        :return:
        """
        log.debug("开始执行设置通知配置信息操作")
        path = '/ugreen/v1/desktop/message/config'
        param_names = ["storage", "system", "power", "security", "desktop", "network", "application", "log",
                       "filemanager",
                       "control"]
        # 通过字典推导，为每个参数名随机生成True或False值，构建参数值的字典
        param_values = {name: random.choice([True, False]) for name in param_names}

        request_data = [{"name": name, "label": name.capitalize() + "服务", "selected": param_values[name]} for name in
                        param_names]
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在设置通知配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def clean_message(self):
        """
        清除通知
        :return:
        """
        log.debug("开始执行清除通知操作")
        path = '/ugreen/v1/desktop/message/clean'
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在清除通知过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.list", check=assert_message)
    def get_user_list(self):
        """
        获取用户列表
        :return:
        """
        log.debug("开始执行获取用户列表操作")
        path = '/ugreen/v1/user/list'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户列表过程中出现异常，异常信息: {e}")
            raise

    def get_user_list_by_role(self, role):
        """
        根据角色获取用户列表
        :param role: 角色 admin、users、guest
        :return:
        """
        try:
            users = self.get_user_list()
            user_list = [user.get('username') for user in users if user.get('role') == role]
            return user_list
        except AttributeError as ae:
            log.error(f"在根据角色获取用户列表过程中出现属性相关异常，可能是获取用户列表的对象或数据结构存在问题，异常信息: {ae}")
            raise
        except KeyError as ke:
            log.error(f"在根据角色获取用户列表过程中出现键值相关异常，可能是用户数据中缺少 'role' 字段等情况，异常信息: {ke}")
            raise
        except Exception as e:
            log.error(f"在根据角色获取用户列表过程中出现其他未分类异常，异常信息: {e}")
            raise

    def get_user_info_by_uid(self, uid):
        """
        根据用户uid获取用户信息
        :param uid: 用户id
        :return:
        """
        try:
            users = self.get_user_list()
            user_info = [user for user in users if user.get('uid') == uid]
            return user_info[0]
        except AttributeError as ae:
            log.error(f"在根据用户uid获取用户信息过程中出现属性相关异常，可能是获取用户列表的对象或数据结构存在问题，异常信息: {ae}")
            raise
        except KeyError as ke:
            log.error(f"在根据用户uid获取用户信息过程中出现键值相关异常，可能是用户数据中缺少 'uid' 字段等情况，异常信息: {ke}")
            raise
        except Exception as e:
            log.error(f"在根据用户uid获取用户信息过程中出现其他未分类异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_nginx_connect(self, hostname, protocol='http', port=9999, http_port=9999, https_port=9443,
                          autoRedirectToHttps=0, http2Enable=1,
                          httpCompressEnable=1, reusePortEnable=0, customMaxConnsEnable=0, customMaxConns=1024,
                          customTitleEnable=0, customTitle="nginx", autoHttp2OptionEnable=0,
                          defaultHttpRedirectEnable=1, defaultHttpsRedirectEnable=1):
        """
        设置nginx网页连接信息
        :param http_port: http端口
        :param https_port: https端口
        :param autoRedirectToHttps: 是否自动跳转到https
        :param http2Enable: 是否启用http2
        :param httpCompressEnable: 是否启用http压缩
        :param reusePortEnable: 是否启用端口复用
        :param customMaxConnsEnable: 是否启用自定义最大连接数
        :param customMaxConns: 自定义最大连接数
        :param customTitleEnable: 是否启用自定义标题
        :param customTitle: 自定义标题
        :param autoHttp2OptionEnable: 是否启用自动http2选项
        :param defaultHttpRedirectEnable: 是否启用默认http重定向
        :param defaultHttpsRedirectEnable: 是否启用默认https重定向
        :return:
        """
        log.debug("开始执行设置nginx网页连接信息操作")
        path = f'{protocol}://{hostname}:{port}/ugreen/v1/connect/nginx/set'
        request_data = {"cumtomPorts": {"http": http_port, "https": https_port},
                        "autoRedirectToHttps": autoRedirectToHttps, "http2Enable": http2Enable,
                        "httpCompressEnable": httpCompressEnable, "reusePortEnable": reusePortEnable,
                        "customMaxConnsEnable": customMaxConnsEnable,
                        "customMaxConns": customMaxConns, "customTitleEnable": customTitleEnable,
                        "customTitle": customTitle,
                        "autoHttp2OptionEnable": autoHttp2OptionEnable,
                        "defaultHttpRedirectEnable": defaultHttpRedirectEnable,
                        "defaultHttpsRedirectEnable": defaultHttpsRedirectEnable}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在设置nginx网页连接信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def start_ftp(self, status=True, enable_ftp=False, enable_ftps=False, port=21, enable_log=False,
                  enable_debug=False):
        """
        开启FTP/FTPS功能
        :return:
        """
        log.debug("开始执行开启FTP/FTPS功能操作")
        path = '/ugreen/v1/file/ftp/start'
        data = {"status": status, "enable_ftp": enable_ftp, "enable_ftps": enable_ftps, "port": port,
                "enable_log": enable_log,
                "enable_debug": enable_debug, "enable_umask": False, "timeout": 300, "enable_pasv_port": False,
                "pasv_min_port": 0, "pasv_max_port": 0, "enable_pasv_ext_ip": False, "pasv_ext_ip": "",
                "enable_fxp": False, "enable_ascii": False, "enable_utf8": True, "enable_local_time": False,
                "enable_max_per_ip": False, "max_per_ip": 2, "enable_rate": False, "max_upload_rate": 0,
                "max_download_rate": 0}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在开启FTP/FTPS功能过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def stop_ftp(self):
        """
        关闭FTP与FTPS功能
        :return:
        """
        log.debug("开始执行开启FTP/FTPS功能操作")
        path = '/ugreen/v1/file/ftp/stop'
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在关闭FTP与FTPS功能过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_ftp_config(self):
        """
        获取FTP配置信息
        :return:
        """
        log.debug("开始执行获取FTP配置信息操作")
        path = '/ugreen/v1/file/ftp/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取FTP配置信息过程中出现异常，异常信息: {e}")
            raise

    def check_ftp_service(self, host, port=21, username="test3", password="Aa123456@"):
        """
        检查FTP服务是否开启
        :param host:
        :param port:
        :param username:
        :param password:
        :return:
        """
        try:
            # 尝试连接到 FTP 服务器
            ftp = ftplib.FTP()
            ftp.connect(host, port)
            # 使用提供的用户名和密码登录
            ftp.login(username, password)
            # 关闭连接
            ftp.quit()
            print(f"使用账号 {username} 成功登录 FTP 服务，服务在 {host}:{port} 上已成功开启。")
            return True
        except ftplib.all_errors as e:
            print(f"连接或登录 FTP 服务时出错: {e}，FTP 服务可能未开启或账号密码错误。")
            return False

    def check_ftps_service(self, host, port=21, username="test3", password="Aa123456@"):
        try:
            # 创建 FTPS 客户端实例
            ftps = FTP_TLS()
            # 连接到 FTPS 服务器
            ftps.connect(host, port)
            # 使用提供的用户名和密码登录
            ftps.login(username, password)
            # 关闭连接
            ftps.quit()
            print(f"使用账号 {username} 成功登录 FTPS 服务，服务在 {host}:{port} 上已成功开启。")
            return True
        except Exception as e:
            print(f"连接或登录 FTPS 服务时出错: {e}，FTPS 服务可能未开启或账号密码错误。")
            return False

    @check_response(ext="data", check=assert_message)
    def get_terminal(self):
        """
        获取终端配置信息
        :return:
        """
        log.debug("开始执行获取终端配置信息操作")
        path = '/ugreen/v1/terminal/get'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取终端配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_terminal(self, ssh_enable=1, ssh_port=22, ssh_permit=2, useSftp=2, encryptLevel=2,
                     telnet_enable=2, telnet_port=23, telnet_permit=2):
        """
        设置终端配置信息
        :param ssh_enable: 1开启，0关闭
        :param ssh_port: ssh端口
        :param ssh_permit: 1仅允许局域网访问，2允许局域网和互联网访问
        :param useSftp: 1开启，0关闭
        :param encryptLevel: 1不加密，2加密
        :param telnet_enable: 1开启，0关闭
        :param telnet_port: telnet端口
        :param telnet_permit: 1仅允许局域网访问，2允许局域网和互联网访问
        :return:
        """
        log.debug("开始执行设置终端配置信息操作")
        path = '/ugreen/v1/terminal/set'
        data = {
            "sshConfig": {"enable": ssh_enable, "port": ssh_port, "permitLanAccessOnly": ssh_permit, "useSftp": useSftp,
                          "encryptLevel": encryptLevel},
            "telnetConfig": {"enable": telnet_enable, "port": telnet_port, "permitLanAccessOnly": telnet_permit}}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置终端配置信息过程中出现异常，异常信息: {e}")
            raise

    def telnet_login(self, host, port=23, username="test3", password="Aa123456@"):
        try:
            # 创建 Telnet 对象并连接到指定主机和端口
            tn = telnetlib.Telnet(host, port)
            # 设置调试级别，便于查看详细的交互信息，在实际使用中可根据需要调整
            tn.set_debuglevel(1)
            # 读取直到出现 "login: " 提示，等待服务器要求输入用户名
            tn.read_until(b"login: ")
            # 发送用户名到 Telnet 服务器
            tn.write(username.encode('ascii') + b"\n")
            # 读取直到出现 "Password: " 提示，等待服务器要求输入密码
            tn.read_until(b"Password: ")
            # 发送密码到 Telnet 服务器
            tn.write(password.encode('ascii') + b"\n")
            # 读取登录后的响应信息，这里设置超时时间为 5 秒，可按需调整
            result = tn.read_until(b"\n", timeout=5).decode('ascii', errors='ignore')
            # 检查响应信息中是否包含登录失败的关键字，若包含则表示登录失败
            if "Login incorrect" in result:
                print("登录失败，用户名或密码错误。")
                tn.close()
                return False
            else:
                print("登录成功。")
                # 这里可以继续执行其他操作，例如发送命令
                tn.write(b"ls\n")  # 发送 "ls" 命令查看目录列表
                output = tn.read_until(b"\n", timeout=5).decode('ascii', errors='ignore')
                print("命令执行结果：", output)
                # 关闭 Telnet 连接
                tn.close()
                return True

        except ConnectionRefusedError:
            print(f"连接被拒绝，可能 Telnet 服务未在 {host}:{port} 上开启。")
            return False
        except TimeoutError:
            print(f"连接超时，无法连接到 {host}:{port}。")
            return False
        except Exception as e:
            print(f"连接过程中出现其他错误: {e}")
            return False

    def backup_restore(self, uid, backup_local=1):
        """
        本地备份（下载备份资料）
        :return:
        """
        log.debug("开始执行本地备份（下载备份资料）操作")
        path = '/ugreen/v1/backup_restore/backupnow'
        params = {"uid": uid, "backup_local": backup_local}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在本地备份（下载备份资料）过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_machine_common(self):
        """
        获取常规信息
        :return:
        """
        log.debug("开始执行获取常规信息操作")
        path = '/ugreen/v1/sysinfo/machine/common'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取常规信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_storage_info(self):
        """
        获取存储信息
        :return:
        """
        log.debug("开始执行获取存储信息操作")
        path = '/ugreen/v1/sysinfo/storage/info'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取存储信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_sysinfo_collect(self):
        """
        获取服务信息
        :return:
        """
        log.debug("开始执行获取服务信息操作")
        path = '/ugreen/v1/sysinfo/collect/getInfo'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取服务信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_machine_hostname(self, hostname):
        """
        修改主机名称
        :return:
        """
        log.debug("开始执行修改主机名称操作")
        path = '/ugreen/v1/sysinfo/machine/hostname'
        data = {"hostname": hostname}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在修改主机名称过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_finder_info(self):
        """
        获取设备分析信息
        :return:
        """
        log.debug("开始执行获取设备分析信息操作")
        path = '/ugreen/v1/sysinfo/finder/get'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取设备分析信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_finder_info(self, improvement_enable, web_find):
        """
        设置设备分析配置信息
        :param improvement_enable: 0关闭，1开启
        :param web_find: 0关闭，1开启
        :return:
        """
        log.debug("开始执行设置设备分析配置信息操作")
        path = '/ugreen/v1/sysinfo/finder/set'
        data = {"improvement_enable": improvement_enable, "web_find": web_find}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置设备分析配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_machine_repair_info(self):
        """
        获取设备保修时间
        :return:
        """
        log.debug("开始执行获取设备保修时间操作")
        path = '/ugreen/v1/sysinfo/machine/repair/status'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取设备保修时间过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_index_info(self):
        """
        获取索引信息
        :return:
        """
        log.debug("开始执行获取索引信息操作")
        path = '/ugreen/v1/idx/info'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取索引信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def rebuild_index(self):
        """
        重建索引
        :return:
        """
        log.debug("开始执行重建索引操作")
        path = '/ugreen/v1/idx/rebuild'
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在重建索引过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_index_detail(self):
        """
        获取索引明细
        :return:
        """
        log.debug("开始执行获取索引信息操作")
        path = '/ugreen/v1/idx/detail'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取索引明细过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def rebuild_thumb(self):
        """
        重新生成缩略图
        :return:
        """
        log.debug("开始执行重新生成缩略图操作")
        path = '/ugreen/v1/idx/thumb/rebuild'
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在重新生成缩略图过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_thumb_set(self):
        """
        获取缩略图配置信息
        :return:
        """
        log.debug("开始执行获取缩略图配置信息操作")
        path = '/ugreen/v1/idx/thumb/set'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取缩略图配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_thumb_set(self, picQuality=1, videoQuality=1):
        """
        设置缩略图配置信息
        :return:
        """
        log.debug("开始执行设置缩略图配置信息操作")
        path = '/ugreen/v1/idx/thumb/set'
        data = {"picQuality": picQuality, "videoQuality": videoQuality}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置缩略图配置信息过程中出现异常，异常信息: {e}")
            raise

    def get_index_status(self, idx):
        """
        获取索引状态
        :param idx:idxInfo、thumbInfo
        :return:
        """
        log.debug("开始执行获取索引状态操作")
        try:
            result = self.get_index_detail()
            if result:
                return result.get(idx).get('status')
        except Exception as e:
            log.error(f"在获取索引明细过程中出现异常，异常信息: {e}")
            raise

    def check_index_status(self, index='idxInfo', status=2, timeout=600):
        """
        校验index状态并等待固定时间
        :param index:idxInfo、thumbInfo
        :param status: 0:未开始 1:进行中 2:成功 3:失败
        :param timeout: 最大等待时间
        """
        log.debug(f"开始校验{index}状态并等待，预期状态: {status}，最大等待时间: {timeout} 秒")
        try:
            elapsed_time = 0
            while elapsed_time < timeout:
                index_status = self.get_index_status(index)
                log.info(f"当前获取到的{index}的状态为: {index_status}")
                if index_status == status:
                    log.debug(f"在 {elapsed_time} 秒内达到预期状态 {status}")
                    return True
                time.sleep(30)
                elapsed_time += 30
                log.info(f"{index}状态为 {index_status}，等待 30 秒后继续校验，已等待 {elapsed_time} 秒")
            raise TimeoutError(f"等待 {timeout} 秒后仍未达到预期状态 {status}")
        except TimeoutError as e:
            log.error(f"等待超时: {e}")
            raise
        except Exception as e:
            log.error(f"获取{index}状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_buzzer_config(self):
        """
        获取蜂鸣器配置信息
        :return:
        """
        log.debug("开始执行获取蜂鸣器配置信息操作")
        path = '/ugreen/v1/hardware/buzzer/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取蜂鸣器配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def set_buzzer_config(self, fan_fault=1, cache_exception=1, system_startup=1, system_shutdown=1,
                          temperature_too_high=1):
        """
        设置蜂鸣器配置信息
        :param fan_fault: 风扇故障
        :param cache_exception: 缓存异常
        :param system_startup: 系统启动
        :param system_shutdown: 系统关闭
        :param temperature_too_high: 温度过高
        :return:
        """
        log.debug("开始执行设置蜂鸣器配置信息操作")
        path = '/ugreen/v1/hardware/buzzer/start'
        data = {"fan_fault": fan_fault, "cache_exception": cache_exception, "system_startup": system_startup,
                "system_shutdown": system_shutdown, "temperature_too_high": temperature_too_high}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在获取蜂鸣器配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_fan_config(self):
        """
        获取风扇配置信息
        :return:
        """
        log.debug("开始执行获取风扇配置信息操作")
        path = '/ugreen/v1/hardware/fan/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取风扇配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def set_fan_config(self, mode=1):
        """
        设置风扇配置信息
        :param mode:1、静音 2、普通  3、全速
        :return:
        """
        log.debug("开始执行设置风扇配置信息操作")
        path = '/ugreen/v1/hardware/fan/start'
        params = {"mode": mode}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在设置风扇配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.info", check=assert_message)
    def get_led_config(self):
        """
        获取LED指示灯配置信息
        :return:
        """
        log.debug("开始执行获取LED指示灯配置信息操作")
        path = '/ugreen/v1/hardware/led/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取LED指示灯配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def set_led_config(self, days_list, time_list, bright):
        """
        设置LED指示灯配置信息
        :param days_list: 每周几执行，例如[1,2,3,4,5,6,7]
        :param time_list: 每天几点执行，例如[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
        :param bright: 亮度，取值范围0-100
        :return:
        """
        log.debug("开始执行设置LED指示灯配置信息操作")
        path = '/ugreen/v1/hardware/led/start'
        data = {"info": [{"days": days_list, "timeConfig": [{"time": time_list, "bright": bright}]}]}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置LED指示灯配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.frequency", check=assert_message)
    def get_cpu_config(self):
        """
        获取电源管理信息
        :return:
        """
        log.debug("开始执行获取电源管理信息信息操作")
        path = '/ugreen/v1/hardware/cpu/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取电源管理信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_cpu_config(self, frequency):
        """
        设置电源管理信息
        :param frequency: 0、高性能 1、平衡 2、节能
        :return:
        """
        log.debug("开始执行设置电源管理信息操作")
        path = '/ugreen/v1/hardware/cpu/frequency'
        data = {"frequency": frequency}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置电源管理信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_power_config(self):
        """
        获取电源配置信息
        :return:
        """
        log.debug("开始执行获取电源配置信息操作")
        path = '/ugreen/v1/hardware/power/config'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取电源配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def set_power_config(self, power_boot=True, wake_on=True, hard_drive_flag=True,
                         hard_drive_time=10, usb_hard_drive_flag=True, usb_hard_drive_time=20,
                         time_switches=[], enable_hard_drive_sleep_log=True, hard_drive_unit="M",
                         usb_hard_drive_unit="M"):
        """
        设置电源配置信息
        :return:
        """
        log.debug("开始执行设置电源配置信息操作")
        path = '/ugreen/v1/hardware/power/start'
        data = {"power_boot": power_boot, "wake_on": wake_on, "hard_drive_flag": hard_drive_flag,
                "hard_drive_unit": hard_drive_unit,
                "hard_drive_time": hard_drive_time, "usb_hard_drive_flag": usb_hard_drive_flag,
                "usb_hard_drive_unit": usb_hard_drive_unit,
                "usb_hard_drive_time": usb_hard_drive_time, "time_switches": time_switches,
                "enable_hard_drive_sleep_log": enable_hard_drive_sleep_log}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置电源配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_terminal_config(self):
        """
        获取终端配置信息
        :return:
        """
        log.debug("开始执行获取终端配置信息操作")
        path = '/ugreen/v1/terminal/get'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取终端配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_terminal_config(self, ssh_enable=1, ssh_port=22, ssh_permitLanAccessOnly=2, useSftp=1, encryptLevel=2,
                            telnet_enable=1, telnet_port=23, telnet_permitLanAccessOnly=2):
        """
        设置终端配置信息
        :param ssh_enable: ssh开关
        :param ssh_port: ssh端口
        :param ssh_permitLanAccessOnly: ssh是否仅允许局域网访问
        :param useSftp: 是否使用sftp
        :param encryptLevel: 加密等级
        :param telnet_enable: telnet开关
        :param telnet_port: telnet端口
        :param telnet_permitLanAccessOnly: telnet是否仅允许局域网访问
        :return:
        """
        log.debug("开始执行设置终端配置信息操作")
        path = '/ugreen/v1/terminal/get'
        data = {"sshConfig": {"enable": ssh_enable, "port": ssh_port, "permitLanAccessOnly": ssh_permitLanAccessOnly,
                              "useSftp": useSftp, "encryptLevel": encryptLevel},
                "telnetConfig": {"enable": telnet_enable, "port": telnet_port,
                                 "permitLanAccessOnly": telnet_permitLanAccessOnly}}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置终端配置信息过程中出现异常，异常信息: {e}")
            raise


system = SystemApi(token, configname=config_name)

if __name__ == "__main__":
    # token = login.login()
    # a = SystemApi(token)
    # result = a.backup_restore('1000')
    # headpic_list = a.get_user_headpic_list()
    # icon = headpic_list[random.randint(0, len(headpic_list) - 1)]
    # icon_stream = a.get_headpic_stream(icon).content
    # print(icon_stream)
    # status = a.desktop_search('应用中心')
    # a.change_user_headpic('1001','08.png')
    # status = a.get_user_language()
    # a.change_user_headpic('1001', icon)
    # print(int(time.time() * 1000))
    pass

